package com.xm.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xm.common.HttpSingleton;
import com.xm.entity.HotHomeEntity;
import com.xm.entity.SearchAppResponse;
import com.xm.entity.SearchDataVO;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.xm.service.impl.BuyXmGoodServiceImpl.getHomeDataList;

/**
 * @Author tianqin
 * @Date 2025/3/14 13:11
 */

@RestController
@CrossOrigin
public class GetDataController {
    @GetMapping("/getHotHomeData")
    private List<String> getHotHomeData() throws IOException, InterruptedException {
        List<String> nameList = new ArrayList<>();
        List<HotHomeEntity.Category> homeDataList = getHomeDataList();
        for (HotHomeEntity.Category datum : homeDataList) {
            List<HotHomeEntity.DataListItem> dataList = datum.getDataList();
            for (HotHomeEntity.DataListItem dataListItem : dataList) {
                if (dataListItem.getPlatformId() == null || dataListItem.getPlatformId() != 741){
                    continue;
                }
               nameList.add(dataListItem.getName());
            }
        }
        return nameList;
    }


    @GetMapping("/searchDataByName")
    private List<SearchDataVO> searchDataByName(String name) throws IOException, InterruptedException {
        List<SearchDataVO> resultList = new ArrayList<>();
        // 假设你已经有HttpClient单例模式获取的方法 HttpSingleton.getInstance()
        HttpClient httpClient = HttpSingleton.getInstance();

        // 构建请求体字符串
        String requestBody = String.format("{\"platformIds\":[],\"pageNum\":1,\"type\":\"0\",\"search\":\"%s\",\"isTransfer\":null,\"goodsTypeList\":[2,3]}",name);

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.x-metash.cn/h5/home/searchApp"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        ObjectMapper objectMapper = new ObjectMapper();
        SearchAppResponse searchAppResponse = objectMapper.readValue(response.body(), SearchAppResponse.class);
        for (SearchAppResponse.Item responseDatum : searchAppResponse.getData()) {
            SearchDataVO searchDataVO = new SearchDataVO();
            searchDataVO.setGoodId(String.valueOf(responseDatum.getArchiveId()));
            searchDataVO.setGoodName(responseDatum.getName());
            resultList.add(searchDataVO);
        }


        return resultList;
    }

}
